package com.winit.openapi.apiadapter.controller.util;

import java.text.ParseException;
import java.util.Comparator;
import java.util.Date;
import java.util.Locale;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.ibm.icu.text.SimpleDateFormat;
import com.winit.openapi.util.DateUtil;
import com.winit.openapi.util.ValidateUtil;

public class JsonComparatorUtil implements Comparator<JSONObject> {

    private static final Logger logger = LoggerFactory.getLogger(JsonComparatorUtil.class);

    @Override
    public int compare(JSONObject json1, JSONObject json2) {
        String date1 = json1.getString("dateOrdered");
        String date2 = json2.getString("dateOrdered");
        long t1 = getDateTime(date1);
        long t2 = getDateTime(date2);

        if (t1 > t2) {
            return -1;
        } else if (t1 < t2) {
            return 1;
        }
        return 0;

    }

    private long getDateTime(String dateStr) {
        long time = Long.valueOf(0);
        if (StringUtils.isEmpty(dateStr)) {
            return time;
        }

        if (ValidateUtil.isLongNumber(dateStr)) {
            return Long.valueOf(dateStr);
        }

        SimpleDateFormat format = null;
        if (dateStr.contains("-")) {

            format = new SimpleDateFormat(DateUtil.FULL_DATE_STRING);
        } else {
            format = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK);
        }

        try {
            Date date = format.parse(dateStr);
            return date.getTime();
        } catch (ParseException e) {
            time = Long.valueOf(0);
            logger.warn("非法的时间格式: " + dateStr);
        }
        return time;

    }
}
